import {updateQueue} from './Component';

/**
 * 给真实DOM添加事件处理函数
 *
 * @param dom
 * @param eventType
 * @param listener
 *
 * 1. 做兼容处理
 * 2. 处理批量更新
 */
export function addEvent(dom,eventType,listener){
  const store = dom.store || (dom.store = {});
  store[eventType] = listener;

  if (!document[eventType]) {
    //没错 都是绑到document上的
    //但17之后不再将事件全部冒泡到document去代理，这和浏览器的改进有关，不再需要代理绑定，浏览器可以对更细粒度的区域进行监听
    document[eventType] = dispatchEvent;
  }
}

//↓ 为什么需要syntheticEvent
//1. 兼容处理
//2. 提高性能(单例  （？emmm）
const syntheticEvent = {
  stopping:false,
  stop(){
    this.stopping = true;
  }
}

function dispatchEvent(event){
  console.log('dispatchEvent---');
  let {target, type} = event;
  const eventType = `on${type}`;

  updateQueue.isBatchingUpdate = true;

  createSyntheticEvent(event);
  while (target){ //之所以要用while 是因为要模拟实现事件冒泡
    const {store} = target;
    const listener = store && store[eventType];
    listener && listener.call(target, syntheticEvent);
    target = target.parentNode
    if(syntheticEvent.stopping) break;
  }
  clearSyntheticEvent(event);

  updateQueue.batchUpdate();
}

function createSyntheticEvent(nativeEvent) {
  for (const eventKey in nativeEvent) {
    syntheticEvent[eventKey] = nativeEvent[eventKey];
  }
}

function clearSyntheticEvent(nativeEvent) {
  for (const eventKey in nativeEvent) {
    syntheticEvent[eventKey] = null;
  }
  syntheticEvent.stopping = false;
}
